<template>
  <el-card>
    <template #header>
      <div class="flex-x-between">
        <span>碳减排</span>
        <el-radio-group v-model="emissionTrendDateRange" size="small">
          <el-radio-button label="近一个月" :value="0" />
          <el-radio-button label="近六个月" :value="1" />
        </el-radio-group>
      </div>
    </template>
    <ECharts :options="emissionTrendEchartsOptions" height="400px" />
  </el-card>
</template>

<script setup>
import RecycleRequetAPI from "@/api/system/recycle-request";


// 访问趋势日期范围（单位：天）
const emissionTrendDateRange = ref(0);
// 访问趋势图表配置
const emissionTrendEchartsOptions = ref();
/**
 * 获取访问趋势数据，并更新图表配置
 */
const fetchVisitTrendData = (dateType) => {
  RecycleRequetAPI.getEmissionStats({
    periodType: dateType
  }).then((data) => {
    updateEmissionTrendEchartsOptions(data);
  });
};

// 监听访问趋势日期范围的变化，重新获取趋势数据
watch(
  () => emissionTrendDateRange.value,
  (newVal) => {
    fetchVisitTrendData(newVal);
  },
  { immediate: true }
);

/**
 * 更新访问趋势图表的配置项
 *
 * @param data - 访问趋势数据
 */
const updateEmissionTrendEchartsOptions = (data) => {
  emissionTrendEchartsOptions.value = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    legend: {
      data: ['碳减排量', '碳减排率'],
      bottom: 0
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.period)
    },
    yAxis: [
      {
        type: 'value',
        name: '减排量 (吨)',
        axisLabel: { formatter: '{value} t' }
      },
      {
        type: 'value',
        name: '减排率 (%)',
        axisLabel: { formatter: '{value} %' }
      }
    ],
    series: [
      {
        name: '碳减排量',
        type: 'bar',
        data: data.map(item => item.reduction.toFixed(2))
      },
      {
        name: '碳减排率',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: data.map(item => item.reductionRate.toFixed(2))
      }
    ]
  };
};
</script>

<style lang="scss" scoped></style>